<template>
  <div class="upload-image">
      <input type="file" ref="upload" style="display:none"  accept="image/*" @change="starUpload">
      <div class="image-box">
        <img src="../../../../static/image/snipaste_20210517_145455.png" alt="">
        <div style="text-align:center;color:#d1d1d1">暂无图片</div> 
        <div style="text-align:center;margin-top: 14px;"> <span class="upload-btn" @click="upload">上传图片</span> </div>
        
      </div>
      <ProgressMain v-if="uploading" :percentage ='percentage'></ProgressMain>
  </div>
</template>

<script>
import { uploadFile, getUploadImage, getUpCode } from '../../../api/axios'
const BYTES_PER_CHUNK = 1024 * 1024 * 1 / 10; // 每个文件切片大小
import SparkMD5 from "spark-md5";
import ProgressMain from './progress'
export default {
  components:{ProgressMain },
  data(){
    return{
      paertArr:[],
      fileMd5:'',
      percentage:0,
      index:1,
      uploading:false,
    }
  },


  methods:{
    upload(){
      this.$refs.upload.click()
    },
    async starUpload(){
      let data = new FormData()
      data.append('apikey','70DABA18-3B05-4EB3-B604-04665ABB3FD6')
      let codeResult = await getUpCode(data)
      if(codeResult.traceId || !codeResult){
        this.$notify.error({
          title: `错误,5秒后自动关闭`,
          message: codeResult.detail,
          duration: 5000
        });
        return
      }
      this.uploading = true
      let files = this.$refs.upload.files[0]
      this.percentage = 0
      this.filesSlice(files)
      let file_total = this.paertArr.length
      // 将进度条分成 total 分
     
      let singleProgress = Math.ceil(100 / file_total)
      
      await this.doIncrementalTest(this.$refs.upload.files[0])
      this.index = 1
      this.Upload(this.paertArr, this.index , files.size , file_total, files.name, singleProgress)
    },
    async Upload(arr, index, size , total, name, singleProgress){
      let formdata = new FormData()
      formdata.append('apikey', '70DABA18-3B05-4EB3-B604-04665ABB3FD6')
      formdata.append('file_size', size)
      formdata.append('file_md5',this.fileMd5)
      formdata.append('file_total', total)
      formdata.append('file_name', name)
      // formdata.append('queue_id', sessionPath)
      formdata.append('file_index', index)
      formdata.append('file_data',arr[index - 1])
      await uploadFile(formdata).then(res=>{
        if(res.traceId){
          this.$notify.error({
                title: `错误,5秒后自动关闭`,
                message: res.detail,
                duration: 5000
          });
          this.uploading = false
          return
        }
        if(res.status == 1){
          this.percentage += singleProgress
          if(this.percentage>=100){
            this.percentage = 99
          }
          this.Upload(arr, index+1, size, total, name ,singleProgress)
        }else{
          this.percentage = 100
          this.uploading = false
          this.$emit('loadingImage')
        }
      })
    },
    doIncrementalTest(input) {
      var _this = this;
      var running = false; //running用于判断是否正在计算md5
      //这里假设直接将文件选择框的dom引用传入
      if (running) {
        return;
      }
      //这里需要用到File的slice( )方法，以下是兼容写法
        var blobSlice =
        File.prototype.slice ||
        File.prototype.mozSlice ||
        File.prototype.webkitSlice,
        file = input,
        chunkSize =104857.6, // 以每片1MB大小来逐次读取
        chunks = Math.ceil(file.size / chunkSize),
        currentChunk = 0,
        spark = new SparkMD5()//创建SparkMD5的实例
      return new Promise((resolve, reject) => {
        let  fileReader = new FileReader();
       fileReader.onload = function(e) {
         spark.appendBinary(e.target.result); // append array buffer
         currentChunk += 1;
         if (currentChunk < chunks) {
           loadNext();
         } else {
           running = false;
           let str = spark.end();
           _this.fileMd5 = str;//赋值md5
           resolve(str)
           return spark.end(); // 完成计算，返回结果
         }
       };
       fileReader.onerror = function() {
         running = false;
         console.log("something went wrong");
       };
       function loadNext() {
         var start = currentChunk * chunkSize,
           end = start + chunkSize >= file.size ? file.size : start + chunkSize;
         fileReader.readAsBinaryString(blobSlice.call(file, start, end));
       }
       running = true;
       loadNext();
      })
    //   console.log("spark============", spark);
    //   console.log("*************", spark.end());
    },
    filesSlice(files) {
      let start = 0;
      let end;
      let partNumber = 0;
      let part = "";
      let paertArr = [];
      let slices = Math.ceil(files.size / BYTES_PER_CHUNK);
      while (start < files.size) {
        end = start + BYTES_PER_CHUNK;
        if (end > files.size) {
          end = files.size;
        }
        var chunk = files.slice(start, end); //切割文件
        paertArr.push(chunk);
        start = end;
        partNumber++;
      }
      this.paertArr = paertArr;
    }
  }
}
</script>

<style lang='scss' scoped>
// .progress{
//   position: absolute;
//   top: 50%;
//   left: 50%;
//   width: 300px;
// }
/deep/ .el-progress-bar{
  width: 95%;
}
.upload-image{
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  background-color: #fff;
  height: 100%;
  .upload-btn{
    cursor: pointer;
    border: 1px solid #ccc;
    padding: 5px 10px;
    margin-top: 10px;
  }
}
</style>